import { PrimaryTableCol, Space, TableRowData } from 'tdesign-vue-next';

import { ActionBarItem } from '@/components/common-action-bar/index.vue';
import { SearchBarItem } from '@/components/common-search-bar/index.vue';
import { t } from '@/locales';
import { tableActionBtn } from '@/utils/action';

/**
 * 将字节大小转换为更易读的文件大小格式，最小单位为KB。
 * @param size 字节大小，必须是正数。
 * @returns 格式化后的文件大小字符串，例如“2.5KB”。
 * @throws 如果输入不是正数，则抛出错误。
 */
const formatFileSize = (size: number) => {
  // 验证输入是否为非负数
  if (typeof size !== 'number' || size < 0) {
    throw new Error('Invalid input: size must be a non-negative number.');
  }

  // 定义单位以及每单位的字节大小
  const units = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB'];
  const BYTE_SIZE = 1024;

  // 将size转换为KB
  size /= BYTE_SIZE;

  // 初始化当前单位索引
  let unitIndex = 0;

  // 循环直到找到正确的单位
  while (size >= BYTE_SIZE && unitIndex < units.length - 1) {
    size /= BYTE_SIZE;
    unitIndex++;
  }

  // 使用toFixed保留两位小数，确保结果的精度
  return `${size.toFixed(2)} ${units[unitIndex]}`;
};

export interface FormItem {
  id?: number;
  name: string;
  letter: string;
  pinyin: string;
  seoTitle: string;
  seoKeywords: string;
  seoDescription: string;
}

export const SEARCH_BAR_DATA: SearchBarItem[] = [
  { component: 'input-number', label: 'ID', name: 'id' },
  { label: 'pages.attachement.size', name: 'size', component: 'select', options: [] },
  { label: 'common.createBy', name: 'operatorId', component: 'select', options: [] },
  { label: 'common.createAt', name: 'createdAt', component: 'daterange', value: [], width: 350, labelWidth: 90 },
];

export const ACTION_BAR_DATA: ActionBarItem[] = [
  {
    component: 'radio-button',
    key: 'viewtype',
    defaultValue: 'list',
    options: [
      { label: '列表', value: 'list', icon: 'view-list' },
      { label: '相册', value: 'album', icon: 'grid-view' },
    ],
  },
  {
    component: 'upload',
  },
];

export const COLUMNS: PrimaryTableCol<TableRowData>[] = [
  { title: 'ID', colKey: 'id', width: 100 },
  { title: () => t('pages.attachement.path'), colKey: 'url', width: 360 },
  {
    title: () => t('pages.attachement.size'),
    colKey: 'size',
    cell(h, props) {
      return props.row.size !== undefined ? formatFileSize(props.row.size) : '';
    },
  },
  { title: () => t('pages.attachement.type'), colKey: 'mimetype' },
  { title: () => t('common.createBy'), colKey: 'operator.username' },
  { title: () => t('common.createAt'), colKey: 'createdAt' },
  {
    title: () => t('common.operation'),
    colKey: 'action',
    width: 150,
    cell(h, { row }) {
      const actionDelete = tableActionBtn({ h, type: 'delete', row, auths: ['content:attachement:delete'] });
      return h(Space, () => {
        return [actionDelete];
      });
    },
  },
];
